/*
 * 文件名：MyBatisPlusConfig.java
 * 版权：Copyright by layne
 * 描述：
 * 修改人：layne
 * 修改时间：2019年5月6日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.bicycle.service.config;

import com.baomidou.mybatisplus.extension.parsers.DynamicTableNameParser;
import com.baomidou.mybatisplus.extension.parsers.ITableNameHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@MapperScan("com.bicycle.service.mapper")
@Configuration
public class MyBatisPlusConfig {

    public static ThreadLocal<String> dynamicTableName = new ThreadLocal<>();


    /**
     * mybatis-plus分页插件 动态表面插件
     *
     * @return
     * @see
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        DynamicTableNameParser dynamicTableNameParser = new DynamicTableNameParser();
        Map<String, ITableNameHandler> tableNameHandlerMap = new HashMap<>();
        //User是数据库表名
        tableNameHandlerMap.put("bicycle_data_order_info", new ITableNameHandler() {
            @Override
            public String dynamicTableName(MetaObject metaObject, String sql, String tableName) {
                return tableName + "_" + dynamicTableName.get();//返回null不会替换 注意 多租户过滤会将它一块过滤不会替换@SqlParser(filter=true) 可不会替换
            }
        });
        tableNameHandlerMap.put("bicycle_data_bicycle_site", new ITableNameHandler() {
            @Override
            public String dynamicTableName(MetaObject metaObject, String sql, String tableName) {
                return tableName + "_" + dynamicTableName.get();//返回null不会替换 注意 多租户过滤会将它一块过滤不会替换@SqlParser(filter=true) 可不会替换
            }
        });
        dynamicTableNameParser.setTableNameHandlerMap(tableNameHandlerMap);
        paginationInterceptor.setSqlParserList(Collections.singletonList(dynamicTableNameParser));

        return paginationInterceptor;
    }
}
